按树状打印二叉树

代码是为了实现二叉树的横向显示问题。这种树形要求先打印右子树,再打印根,最后打印左子树,顺序恰为逆中序顺序。这种输出格式,结点的左右位置与结点的层深有关,故算法中设置了一个表示当前根节点层深的参数,以控制输出结点的左右位置。

示意图:

代码如下:

 

#include  < stdio.h >
#include 
< stdlib.h >
#define  OVERFLOW -2
#define  INFEASIBLE -1
#define  ERROR 0
#define  OK 1
#define  TRUE 1
#define  FALSE 0

typedef 
char  TElemType;
TElemType Nil
= ' # ' ;

typedef 
struct  BiTNode
{
    TElemType data;
    BiTNode 
*lchild,*rchild;
}
BiTNode, * BiTree;

int  InitBiTree(BiTree  * T)
{
    
*T=NULL;
    
return OK;
}

void  CreateBiTree(BiTree  * T)
{
    TElemType ch;
    scanf(
"%c",&ch);
    
if(ch==Nil)
        (
*T)=NULL;
    
else
    
{
        (
*T)=(BiTree)malloc(sizeof(BiTNode));
        
if(!(*T))
            exit(OVERFLOW);
        (
*T)->data=ch;
        CreateBiTree(
&(*T)->lchild);
        CreateBiTree(
&(*T)->rchild);
    }

}

 
void  PrintTree(BiTree  * T, int  Layer)
 
{/*按竖向树状打印的二叉树*/
     
int i;
     
if(*T==NULL)
         
return;
     PrintTree(
&(*T)->rchild,Layer+1);
     
for(i=0;i<Layer;i++)    
         printf(
"  ");
     printf(
"%c ",(*T)->data);    //按逆中序输出结点,用层深决定结点的左右位置
     PrintTree(&(*T)->lchild,Layer+1);
 }


 
void  main()
 
{
     BiTNode
* T;
     InitBiTree(
&T);
     printf(
"请先序输入二叉树(如:AB###表示A为根结点,B为左子树的二叉树) ");
     CreateBiTree(
&T);
     PrintTree(
&T,0);
 }


  • 0
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值